package com.sailfish.springbootdemo.service.db7.Impl;


import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db7.*;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db7.*;
import com.sailfish.springbootdemo.service.db7.CommonService;
import com.sailfish.springbootdemo.service.db7.TbFlowProcessMainService;
import com.sailfish.springbootdemo.service.db7.TbTemplateService;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;

@Service
public class TbTemplateServiceImpl implements TbTemplateService {


    @Autowired
    private TbTemplateDao tbTemplateDao;

    @Autowired
    private TbTemplateVersionDao tbTemplateVersionDao;

    @Autowired
    private TbDataDictionaryDao tbDataDictionaryDao;

    @Autowired
    private CommonService commonService;

    @Autowired
    private TbFlowDetailDao tbFlowDetailDao;

    @Autowired
    private TbFlowProcessDetailDao tbFlowProcessDetailDao;

    @Autowired
    private  TbFlowProcessMainDao tbFlowProcessMainDao;


    @Autowired
    private  TbFlowProcessRecordsDao tbFlowProcessRecordsDao;

    @Autowired
    private TbFlowProcessMainService tbFlowProcessMainService;

    @Override
    public Result getTbTemplateByVersion(String data) {

        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                String _template_type = jsonObject.getString("template_type");

                if (StringUtils.isEmpty(_template_type)) {
                    return ResultUtil.error(500, "template_type 不能为空", "", null);
                }
                String _version = jsonObject.getString("version");

                if (StringUtils.isEmpty(_version)) {
                    return ResultUtil.error(500, "version 不能为空", "", null);
                }

                List<TbTemplate> list= tbTemplateDao.getTbTemplateByVersion(_template_type,_version);

                return ResultUtil.success(commonService.buildTree2(list));
            }
            else
            {
                return ResultUtil.error(500, "参数为空", "", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager7")
    @Override
    public Result createNewTemplate(String data) {

        try {

            //解析Json字符串
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                String _template_type = jsonObject.getString("template_type");

                if (StringUtils.isEmpty(_template_type)) {
                    return ResultUtil.error(500, "template_type 不能为空", "", null);
                }

                //获取审核流程
                List<TbFlowDetail> listFlow= tbFlowDetailDao.getFolwListByType(_template_type);

                //如果没有获取到审核流程就报错,说要先维护审核流程.
                //预留开关字段

                boolean IsOpenApprover=true;
                if(IsOpenApprover)
                {
                    if (listFlow == null || listFlow.size() == 0) {
                        return ResultUtil.error(500, "请先维护审核流程", "", null);
                    }
                }

                //先去查询一下当前最新版本是什么
                List<TbTemplateVersion> listVersion = tbTemplateVersionDao.getNewestTemplateVersion(_template_type);

                LocalDate now = LocalDate.now();
                String nowYear = String.valueOf(now.getYear());

                //定义版本号
                String _version = "";
                //定义排序号
                Integer _sort=1;

                //找到了以后就处理,在原来的基础上加1
                if (listVersion!=null && listVersion.size()>0) {
                    TbTemplateVersion tbTemplateVersion = listVersion.get(0);

                    String temp_version = tbTemplateVersion.getVersion();
                    String[] parts = temp_version.split("_");
                    String year = parts[0];
                    String versionNum = parts[1];

                    if (nowYear.equals(year)) {
                        //如果年份相同,则直接在原来的基础上加1
                        int versionNumInt = Integer.parseInt(versionNum.substring(1));
                        versionNumInt++;

                        String newVersionNum = "T" + String.format("%02d", versionNumInt);
                        _version = year + "_" + newVersionNum;

                        Integer temp_sort=tbTemplateVersion.getSort();
                        _sort=temp_sort+1;
                    }
                    else
                    {
                        //如果年份不同,则从T01开始
                        _version= nowYear+"_T01";
                    }
                }
                //没有找到的话就从1开始
                else
                {
                    _version= nowYear+"_T01";
                }
                //处理完成版本号以后就是根据不同的类别去获取所有的数据了
                //先获取所有父节点的数据,然后再根据父节点数据去用递归查所有的数据

                //所有的父节点数据
                List<TbDataDictionary> listDicParent= tbDataDictionaryDao.getDataDictionaryByTemplateType(_template_type);

                //所有的节点数据
                List<TbDataDictionary> listAll= tbDataDictionaryDao.getAllDataDictionaryList();

                List<TbDataDictionary> listAllChildren = commonService.getAllChildren(listAll, listDicParent);

                //生成模板的lsit
                List<TbTemplate> tbTemplateList=new ArrayList<>();
                for (TbDataDictionary dataDictionary : listAllChildren) {
                    TbTemplate tbTemplate = new TbTemplate();

                    // 将 TbDataDictionary 的字段值赋值给 TbTemplate 的字段
                    tbTemplate.setVersion(_version);
                    tbTemplate.setTemplate_type(_template_type);
                    tbTemplate.setParent_id(dataDictionary.getParent_id());
                    tbTemplate.setParam_name(dataDictionary.getParam_name());
                    tbTemplate.setParam_name_en(dataDictionary.getParam_name_en());
                    tbTemplate.setParam_key(dataDictionary.getParam_key());
                    tbTemplate.setParent_param_key(dataDictionary.getParent_param_key());
                    tbTemplate.setParam_type(dataDictionary.getParam_type());
                    tbTemplate.setLevel(dataDictionary.getLevel());
                    tbTemplate.setSelect_level(dataDictionary.getSelect_level());
                    tbTemplate.setParent_select_id(dataDictionary.getParent_select_id());
                    tbTemplate.setTip(dataDictionary.getTip());
                    tbTemplate.setRemark(dataDictionary.getRemark());
                    tbTemplate.setCreate_user(UserHeaderHolder.getUserId());
                    tbTemplate.setCreate_time(new Date());
                    /**tbTemplate.setUpdate_user(dataDictionary.getUpdate_user());
                    tbTemplate.setUpdate_time(dataDictionary.getUpdate_time());*/
                    tbTemplate.setStatus(dataDictionary.getStatus());
                    tbTemplate.setSort(dataDictionary.getSort());
                    tbTemplate.setIs_value(dataDictionary.getIs_value());

                    tbTemplateList.add(tbTemplate);
                }

                //String _flow_no = UUID.randomUUID().toString().replaceAll("-", "");

                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String currentDate = sdf.format(new Date());
                TbFlowProcessMain   byFlowNo = tbFlowProcessMainDao.getByFlowNo(currentDate);
                int currentSeq = 0;
                String _flow_no = "";
                if (byFlowNo != null) {
                    currentSeq = byFlowNo.getSeq();
                }
                currentSeq++;
                //添加审批记录
                _flow_no = currentDate + String.format("%05d", currentSeq);

                TbTemplateVersion tbTemplateVersion=new TbTemplateVersion();
                tbTemplateVersion.setVersion(_version);
                tbTemplateVersion.setTemplate_type(_template_type);
                tbTemplateVersion.setCreate_user(UserHeaderHolder.getUserId());
                tbTemplateVersion.setCreate_time(new Date());
                tbTemplateVersion.setSort(_sort);
                tbTemplateVersion.setFlow_no(_flow_no);
                tbTemplateVersion.setStatus(1);

                //写入审核流程信息
                List<TbFlowProcessDetail> listFlowTemplate =new ArrayList<>();

                for (TbFlowDetail flow : listFlow) {
                    listFlowTemplate.add(new TbFlowProcessDetail(
                            _flow_no,
                            flow.flow_type,
                            flow.flow_name,
                            flow.flow_level,
                            flow.flow_approver,
                            1,
                            flow.sort,
                            UserHeaderHolder.getUserId(),
                            new Date()));
                };

                //获取当前流程的第一个对象
                TbFlowDetail firstFlow = listFlow.get(0);

                //写入主表信息
                TbFlowProcessMain tbFlowProcessMain = new TbFlowProcessMain();
                tbFlowProcessMain.setFlow_no(_flow_no);
                tbFlowProcessMain.setFlow_type(_template_type);
                tbFlowProcessMain.setSeq(currentSeq);
                tbFlowProcessMain.setNow_level(firstFlow.getFlow_level());
                tbFlowProcessMain.setNow_approver(firstFlow.getFlow_approver());
                tbFlowProcessMain.setStatus(1);
                tbFlowProcessMain.setCreate_time(new Date());
                tbFlowProcessMain.setCreate_user(UserHeaderHolder.getUserId());

                tbFlowProcessMainDao.insertFlowProcessMain(tbFlowProcessMain);

                //写入模板的流程
                tbFlowProcessDetailDao.insertFlowTemplateBatch(listFlowTemplate);

                //写入版本记录信息
                tbTemplateVersionDao.insertTemplateVersion(tbTemplateVersion);

                tbTemplateDao.insertTemplateBatch(tbTemplateList);

                //写入流程历史记录表

                TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();
                tbFlowProcessRecords.setFlow_no(_flow_no);
                tbFlowProcessRecords.setFlow_type(_template_type);
                //tbFlowProcessRecords.setFlow_name(firstFlow.getFlow_name());
                //tbFlowProcessRecords.setFlow_level(firstFlow.getFlow_level());
                tbFlowProcessRecords.setFlow_approver(firstFlow.getFlow_approver());
                tbFlowProcessRecords.setResult("待审核");
                tbFlowProcessRecords.setRemark("新建审批流程");
                tbFlowProcessRecords.setSeq(1);
                tbFlowProcessRecords.setCreate_time(new Date());
                tbFlowProcessRecords.setCreate_user(UserHeaderHolder.getUserId());

                tbFlowProcessRecordsDao.insertFlowProcessRecords(tbFlowProcessRecords);

                // 创建一个空的字符串
                StringBuilder jsonBuilder = new StringBuilder();

                // 拼接JSON字符串的各个部分
                jsonBuilder.append("{");
                jsonBuilder.append("\"flow_no\":");
                jsonBuilder.append("\"").append(_flow_no).append("\"");
                jsonBuilder.append("}");

                // 将拼接好的JSON字符串转换为String类型
                String flowNoJson = jsonBuilder.toString();
                //自动审核
                //流程有多少个节点就要审核多少次
                for (int i = 0; i < listFlow.size(); i++) {

                    tbFlowProcessMainService.approveFlow(flowNoJson);
                }


                return ResultUtil.success("生成模板成功");
            }
            else
            {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }

    }

    @Override
    public Result compareTemplate(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                String _template_type = jsonObject.getString("template_type");

                if (StringUtils.isEmpty(_template_type)) {
                    return ResultUtil.error(500, "template_type 不能为空", "", null);
                }
                String _version = jsonObject.getString("version");

                if (StringUtils.isEmpty(_version)) {

                    return ResultUtil.success("false");
                    //return ResultUtil.error(500, "version 不能为空", "", null);
                }

                //查询数据字典的最新数据过来
                //这个只是主信息
                List<TbDataDictionary> listMain = tbDataDictionaryDao.getDataDictionaryByTemplateType(_template_type);

                List<TbDataDictionary> listAll = tbDataDictionaryDao.getAllDataDictionaryList2(2);

                List<TbDataDictionary> listResult= commonService.getAllChildren(listAll, listMain);

                //查询模板的数据过来
                List<TbTemplate> listTemplate= tbTemplateDao.getTbTemplateByVersion2(_template_type,_version,2);
                List<TbDataDictionary> trans=new ArrayList<>();

                for (TbTemplate a : listTemplate) {
                    trans.add(new TbDataDictionary(
                            a.parent_id,
                            a.param_name,
                            a.param_name_en,
                            a.param_key,
                            a.parent_param_key,
                            a.param_type,
                            a.level,
                            a.select_level,
                            a.parent_select_id));
                }

                boolean IsMatch=true;

                if(IsMatch)
                {
                    //循环listResult
                    for (TbDataDictionary a : listResult) {
                        if (!trans.contains(a)) {
                            IsMatch=false;
                            break;
                        }
                    }

                }

                if(IsMatch)
                {
                    for (TbDataDictionary a : trans) {
                        if (!listResult.contains(a)) {
                            IsMatch=false;
                            break;
                        }
                    }
                }

                return ResultUtil.success(String.valueOf(IsMatch));
            }
            else
            {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }


    @Override
    public Result getNewestVersionTbTemplate(String data) {

        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                String _template_type = jsonObject.getString("template_type");

                if (StringUtils.isEmpty(_template_type)) {
                    return ResultUtil.error(500, "template_type 不能为空", "", null);
                }
                //获取最新版本的版本号
                List<TbTemplateVersion> list = tbTemplateVersionDao.getNewestTemplateVersion2(_template_type);

                if(list!=null && list.size()>0)
                {
                    String _version= list.get(0).getVersion();
                    List<TbTemplate> listResult= tbTemplateDao.getPublishedTbTemplateByVersion(_template_type,_version);
                    /** 20251105 推送接口独立出来
                    //增加判断.如果数据字典那边维护成了1，就代表不需要显示，要在这个list中去除
                    List<TbDataDictionary> listAll = tbDataDictionaryDao.getAllDataDictionaryList2(2);

                    if(listAll!=null&&listAll.size()>0)
                    {
                        Set<String> removeParamKeys = new HashSet<>();
                        for (TbDataDictionary dict : listAll) {
                            // 检查 is_show 是否为 1（非空且值为1）
                            if (dict.getIs_show() != null && dict.getIs_show() == 1) {
                                removeParamKeys.add(dict.getParam_key());
                            }
                        }

                        listResult.removeIf(template ->
                                removeParamKeys.contains(template.getParam_key())
                        );
                    }*/
                    return ResultUtil.success(commonService.buildTree2(listResult));
                }
                else
                {
                    return ResultUtil.error(500, "没有找到该模板类型", "", null);
                }
            }
            else
            {
                return ResultUtil.error(500, "参数为空", "", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getNewestVersionTbTemplateForPush(String data) {

        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                String _template_type = jsonObject.getString("template_type");

                if (StringUtils.isEmpty(_template_type)) {
                    return ResultUtil.error(500, "template_type 不能为空", "", null);
                }
                //获取最新版本的版本号
                List<TbTemplateVersion> list = tbTemplateVersionDao.getNewestTemplateVersion2(_template_type);

                if(list!=null && list.size()>0)
                {
                    String _version= list.get(0).getVersion();
                    List<TbTemplate> listResult= tbTemplateDao.getPublishedTbTemplateByVersion(_template_type,_version);

                    //增加判断.如果数据字典那边维护成了1，就代表不需要显示，要在这个list中去除
                    List<TbDataDictionary> listAll = tbDataDictionaryDao.getAllDataDictionaryList2(2);

                    if(listAll!=null&&listAll.size()>0)
                    {
                        Set<String> removeParamKeys = new HashSet<>();
                        for (TbDataDictionary dict : listAll) {
                            // 检查 is_show 是否为 1（非空且值为1）
                            if (dict.getIs_show() != null && dict.getIs_show() == 1) {
                                removeParamKeys.add(dict.getParam_key());
                            }
                        }

                        listResult.removeIf(template ->
                                removeParamKeys.contains(template.getParam_key())
                        );
                    }

                    return ResultUtil.success(commonService.buildTree2(listResult));
                }
                else
                {
                    return ResultUtil.error(500, "没有找到该模板类型", "", null);
                }
            }
            else
            {
                return ResultUtil.error(500, "参数为空", "", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

}
